package com.bangbang.filter;


import com.bangbang.configresult.Result;
import com.bangbang.configresult.ResultEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class RequestFilter extends ZuulFilter {
    //每秒产生3个令牌
    // 谷歌
    private static final RateLimiter RATE_LIMITER = RateLimiter.create(3);
    //    过滤器的类型
//    1.pre 表示在路由之前过滤
//    2.touting 表示在路由之时过滤
//    3.post 表示路由之后
//    4.error 表示出现错误之后 过滤
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
//    过滤器的顺序  (在有多个过滤的方法的时候---只有一个过滤就无所谓了)从小到大的顺序执行过滤  0-1之间
    @Override
    public int filterOrder() {
        return 1;
    }
//  过滤器的开关 false 表示关掉当前的过滤
    @Override
    public boolean shouldFilter() {
        return true;
    }
//  真正要执行的的过滤的功能
    @Override
    public Object run() throws ZuulException {
        //获取当前线程请求上下文类
        RequestContext requestContext = RequestContext.getCurrentContext();
        System.out.println("获取令牌");
        boolean tryAcquire = RATE_LIMITER.tryAcquire();
        // 如果获取不到就直接停止
        if(!tryAcquire){
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
            //获取response
            HttpServletResponse response = requestContext.getResponse();
            try {
                response.setContentType("text/html;charset=utf-8");
                ObjectMapper objectMapper = new ObjectMapper(); //类似于fastJSON  用于转换
                Result result = Result.buildResult(ResultEnum.TOOMANY).setResult("用户未登录，无法访问服务,请先登录");
                response.getWriter().write(objectMapper.writeValueAsString(result));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
